import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectModel } from 'nest-typegoose';
import { ReturnModelType } from '@typegoose/typegoose';
import { Carousel } from '@libs/db/models/carousel.model';

@Injectable()
export class CarouselService {
  constructor(
    @InjectModel(Carousel)
    private readonly carouselModel: ReturnModelType<typeof Carousel>,
  ) {}

  /**
   * 创建轮播图
   * @param createCarouselDto - 创建轮播图的数据
   * @returns 创建的轮播图信息
   */
  async create(createCarouselDto: Partial<Carousel>): Promise<Carousel> {
    try {
      const carousel = new this.carouselModel(createCarouselDto);
      return await carousel.save();
    } catch (error) {
      console.error('创建轮播图失败:', error);
      throw new HttpException(
        `创建轮播图失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 分页查询轮播图列表
   * @param pageNum - 页码
   * @param pageSize - 每页数量
   * @param group - 分组过滤
   * @returns 轮播图列表和分页信息
   */
  async findAll(
    pageNum: number = 1,
    pageSize: number = 10,
    group?: string,
  ): Promise<{ data: Carousel[]; total: number; pageNum: number; pageSize: number }> {
    try {
      const skip = (pageNum - 1) * pageSize;
      const filter: any = {};
      
      if (group) {
        filter.group = { $regex: group, $options: 'i' };
      }

      const [data, total] = await Promise.all([
        this.carouselModel
          .find(filter)
          .sort({ sort: 1, createdAt: -1 })
          .skip(skip)
          .limit(pageSize)
          .exec(),
        this.carouselModel.countDocuments(filter).exec(),
      ]);

      return {
        data,
        total,
        pageNum,
        pageSize,
      };
    } catch (error) {
      console.error('查询轮播图列表失败:', error);
      throw new HttpException(
        `查询轮播图列表失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 获取所有轮播图（不分页）
   * @param group - 分组过滤
   * @returns 轮播图列表
   */
  async findAllWithoutPagination(group?: string): Promise<Carousel[]> {
    try {
      const filter: any = {};
      
      if (group) {
        filter.group = { $regex: group, $options: 'i' };
      }

      return await this.carouselModel
        .find(filter)
        .sort({ sort: 1, createdAt: -1 })
        .exec();
    } catch (error) {
      console.error('查询所有轮播图失败:', error);
      throw new HttpException(
        `查询所有轮播图失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 根据ID查询轮播图详情
   * @param id - 轮播图ID
   * @returns 轮播图详情
   */
  async findOne(id: string): Promise<Carousel> {
    try {
      const carousel = await this.carouselModel.findById(id).exec();
      if (!carousel) {
        throw new HttpException('轮播图不存在', HttpStatus.NOT_FOUND);
      }
      return carousel;
    } catch (error) {
      console.error('查询轮播图详情失败:', error);
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException(
        `查询轮播图详情失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 更新轮播图
   * @param id - 轮播图ID
   * @param updateCarouselDto - 更新数据
   * @returns 更新后的轮播图信息
   */
  async update(id: string, updateCarouselDto: Partial<Carousel>): Promise<Carousel> {
    try {
      const carousel = await this.carouselModel
        .findByIdAndUpdate(id, updateCarouselDto, { new: true })
        .exec();
      
      if (!carousel) {
        throw new HttpException('轮播图不存在', HttpStatus.NOT_FOUND);
      }
      
      return carousel;
    } catch (error) {
      console.error('更新轮播图失败:', error);
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException(
        `更新轮播图失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 删除轮播图
   * @param id - 轮播图ID
   * @returns 删除结果
   */
  async remove(id: string): Promise<{ message: string }> {
    try {
      const result = await this.carouselModel.findByIdAndDelete(id).exec();
      if (!result) {
        throw new HttpException('轮播图不存在', HttpStatus.NOT_FOUND);
      }
      return { message: '轮播图删除成功' };
    } catch (error) {
      console.error('删除轮播图失败:', error);
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException(
        `删除轮播图失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 批量删除轮播图
   * @param ids - 轮播图ID数组
   * @returns 删除结果
   */
  async removeMany(ids: string[]): Promise<{ message: string; deletedCount: number }> {
    try {
      if (!ids || ids.length === 0) {
        throw new HttpException('请提供要删除的轮播图ID', HttpStatus.BAD_REQUEST);
      }

      const result = await this.carouselModel.deleteMany({ _id: { $in: ids } }).exec();
      
      return {
        message: '批量删除轮播图成功',
        deletedCount: result.deletedCount,
      };
    } catch (error) {
      console.error('批量删除轮播图失败:', error);
      if (error instanceof HttpException) {
        throw error;
      }
      throw new HttpException(
        `批量删除轮播图失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}